﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

using BOSS.Framework.Search;
using BOSS.Framework.Search.Context;
using BOSS.Domain.Customers;
using BOSS.Dao.Customers;

namespace BOSS.Dao.NHibernate.Customers
{
    public class CustomerAccountDao : EntityDao<CustomerAccount, int>, ICustomerAccountDao
    {
        #region ISearchSupport<CustomerAccount> 成员

        public IList<CustomerAccount> SelectBySearch(ISearchContext context, out int totalCount)
        {
            int count = 0;

            string customerNameOrAccountNumber = context.GetFilterTermValueAsString("CustomerNameOrAccountNumber");

            IList<CustomerAccount> customers = this.HibernateTemplate.ExecuteFind<CustomerAccount>(delegate(ISession session)
            {
                ICriteria criteria = session.CreateCriteria(typeof(CustomerAccount), "ca")
                                            .CreateAlias("ca.Customer", "cac");

                if (!string.IsNullOrEmpty(customerNameOrAccountNumber))
                {
                    criteria.Add(Expression.Or(Expression.Like("ca.AccountNumber", customerNameOrAccountNumber, MatchMode.Anywhere), Expression.Like("cac.Name", customerNameOrAccountNumber, MatchMode.Anywhere)));
                }

                count = criteria.SetProjection(Projections.Count("Id").SetDistinct()).UniqueResult<int>();
                if (count == 0)
                {
                    return new List<CustomerAccount>();
                }

                criteria.SetProjection(new IProjection[] { null });
                criteria.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);

                return criteria.SetFirstResult(context.PageSize * (context.PageIndex - 1))
                        .SetMaxResults(context.PageSize)
                        .List<CustomerAccount>();
            });

            totalCount = count;
            return customers;
        }

        #endregion
    }
}
